import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Grid,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Typography,
  Divider,
  Switch,
  FormControlLabel,
  Autocomplete,
  InputAdornment,
  Avatar,
  IconButton,
  Chip,
  Alert,
  Skeleton,
} from '@mui/material';
import {
  Save as SaveIcon,
  Cancel as CancelIcon,
  Person as PersonIcon,
  Email as EmailIcon,
  Phone as PhoneIcon,
  PhotoCamera as PhotoCameraIcon,
} from '@mui/icons-material';
import { useNavigate, useParams } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

import {
  UpdateUserRequest,
  Status,
} from '@/types';
import { useAuth, useAppNotifications } from '@/stores';
import { userService } from '@/services/userService';
import { PageHeader } from '@/components/common/PageHeader';

// 表单验证模式（编辑时密码可选）
const userFormSchema = z.object({
  username: z.string()
    .min(3, '用户名不能少于3个字符')
    .max(50, '用户名不能超过50个字符')
    .regex(/^[a-zA-Z0-9_-]+$/, '用户名只能包含字母、数字、下划线和横线'),
  profile: z.object({
    firstName: z.string().min(1, '名字不能为空'),
    lastName: z.string().min(1, '姓氏不能为空'),
    email: z.string().email('请输入有效的邮箱地址'),
    phone: z.string().optional(),
    avatar: z.string().optional(),
  }),
  status: z.enum(['active', 'inactive', 'pending', 'suspended']),
  roles: z.array(z.string()).min(1, '请至少分配一个角色'),
  departments: z.array(z.string()).optional(),
  positions: z.array(z.string()).optional(),
  organizationId: z.string().min(1, '请选择所属组织'),
  security: z.object({
    twoFactorEnabled: z.boolean(),
    loginNotification: z.boolean(),
  }),
  preferences: z.object({
    language: z.string(),
    timezone: z.string(),
    theme: z.enum(['light', 'dark', 'auto']),
    dateFormat: z.string(),
    timeFormat: z.enum(['12h', '24h']),
    notifications: z.object({
      email: z.boolean(),
      sms: z.boolean(),
      push: z.boolean(),
    }),
  }),
});

type UserFormData = z.infer<typeof userFormSchema>;

const UserEditPage: React.FC = () => {
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const queryClient = useQueryClient();
  const { hasPermission, currentTenant } = useAuth();
  const { showToast } = useAppNotifications();

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [avatarPreview, setAvatarPreview] = useState<string>('');

  // 表单控制
  const {
    control,
    handleSubmit,
    formState: { errors },
    reset,
    setValue,
  } = useForm<UserFormData>({
    resolver: zodResolver(userFormSchema),
  });

  // 获取用户详情
  const {
    data: userData,
    isLoading: userLoading,
    error: userError,
  } = useQuery({
    queryKey: ['user', id],
    queryFn: () => userService.getUser(id!),
    enabled: !!id,
  });

  // 获取组织列表
  const { data: organizationsData } = useQuery({
    queryKey: ['organizations', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/organizations?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 获取角色列表
  const { data: rolesData } = useQuery({
    queryKey: ['roles', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/roles?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 获取部门列表
  const { data: departmentsData } = useQuery({
    queryKey: ['departments', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/departments?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 获取岗位列表
  const { data: positionsData } = useQuery({
    queryKey: ['positions', { tenantId: currentTenant?.id }],
    queryFn: () => fetch(`/api/positions?tenantId=${currentTenant?.id}`).then(res => res.json()),
    enabled: !!currentTenant,
  });

  // 当用户数据加载完成时，设置表单默认值
  useEffect(() => {
    if (userData?.data) {
      const user = userData.data;
      setAvatarPreview(user.profile.avatar || '');
      reset({
        username: user.username,
        profile: {
          firstName: user.profile.firstName,
          lastName: user.profile.lastName,
          email: user.profile.email,
          phone: user.profile.phone || '',
          avatar: user.profile.avatar || '',
        },
        status: user.status,
        roles: user.roles || [],
        departments: user.departments || [],
        positions: user.positions || [],
        organizationId: user.organizationId,
        security: {
          twoFactorEnabled: user.security?.twoFactorEnabled || false,
          loginNotification: user.security?.loginNotification ?? true,
        },
        preferences: {
          language: user.preferences?.language || 'zh-CN',
          timezone: user.preferences?.timezone || 'Asia/Shanghai',
          theme: user.preferences?.theme || 'light',
          dateFormat: user.preferences?.dateFormat || 'YYYY-MM-DD',
          timeFormat: user.preferences?.timeFormat || '24h',
          notifications: {
            email: user.preferences?.notifications?.email ?? true,
            sms: user.preferences?.notifications?.sms ?? false,
            push: user.preferences?.notifications?.push ?? true,
          },
        },
      });
    }
  }, [userData, reset]);

  // 更新用户
  const updateMutation = useMutation({
    mutationFn: (data: UpdateUserRequest) => userService.updateUser(id!, data),
    onSuccess: (response) => {
      showToast({
        type: 'success',
        title: '更新成功',
        message: '用户信息已成功更新',
      });
      queryClient.invalidateQueries(['users']);
      queryClient.invalidateQueries(['user', id]);
      navigate('/users');
    },
    onError: (error: any) => {
      showToast({
        type: 'error',
        title: '更新失败',
        message: error.message || '更新用户时发生错误',
      });
    },
  });

  // 提交表单
  const onSubmit = async (data: UserFormData) => {
    if (!hasPermission('user.edit')) {
      showToast({
        type: 'error',
        title: '权限不足',
        message: '您没有编辑用户的权限',
      });
      return;
    }

    setIsSubmitting(true);
    try {
      const requestData: UpdateUserRequest = {
        ...data,
        profile: {
          ...data.profile,
          fullName: `${data.profile.lastName}${data.profile.firstName}`,
        },
      };
      await updateMutation.mutateAsync(requestData);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 处理头像上传
  const handleAvatarChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const result = e.target?.result as string;
        setAvatarPreview(result);
        setValue('profile.avatar', result);
      };
      reader.readAsDataURL(file);
    }
  };

  if (!id) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">用户ID参数缺失</Alert>
      </Box>
    );
  }

  if (!currentTenant) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="warning">请先选择租户</Alert>
      </Box>
    );
  }

  if (userError) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">
          加载用户信息失败：{(userError as any).message}
        </Alert>
      </Box>
    );
  }

  if (userLoading) {
    return (
      <Box sx={{ p: 3 }}>
        <PageHeader
          title="编辑用户"
          description="编辑用户信息"
          breadcrumbs={[
            { label: '首页', path: '/' },
            { label: '用户管理', path: '/users' },
            { label: '编辑用户' },
          ]}
        />
        <Card>
          <CardContent>
            <Grid container spacing={3}>
              {Array.from({ length: 12 }).map((_, index) => (
                <Grid item xs={12} md={6} key={index}>
                  <Skeleton height={56} />
                </Grid>
              ))}
            </Grid>
          </CardContent>
        </Card>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3 }}>
      <PageHeader
        title="编辑用户"
        description={`编辑用户：${userData?.data?.profile.fullName}`}
        breadcrumbs={[
          { label: '首页', path: '/' },
          { label: '用户管理', path: '/users' },
          { label: '编辑用户' },
        ]}
      />

      <Card>
        <CardContent>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Grid container spacing={3}>
              {/* 基本信息 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom>
                  基本信息
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              {/* 头像上传 */}
              <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center', mb: 2 }}>
                <Box sx={{ position: 'relative', display: 'inline-block' }}>
                  <Avatar
                    src={avatarPreview}
                    sx={{ width: 100, height: 100 }}
                  >
                    <PersonIcon sx={{ fontSize: 50 }} />
                  </Avatar>
                  <IconButton
                    color="primary"
                    component="label"
                    sx={{
                      position: 'absolute',
                      bottom: 0,
                      right: 0,
                      backgroundColor: 'background.paper',
                      '&:hover': {
                        backgroundColor: 'action.hover',
                      },
                    }}
                  >
                    <PhotoCameraIcon />
                    <input
                      type="file"
                      hidden
                      accept="image/*"
                      onChange={handleAvatarChange}
                    />
                  </IconButton>
                </Box>
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="profile.lastName"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="姓氏"
                      fullWidth
                      required
                      error={!!errors.profile?.lastName}
                      helperText={errors.profile?.lastName?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="profile.firstName"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="名字"
                      fullWidth
                      required
                      error={!!errors.profile?.firstName}
                      helperText={errors.profile?.firstName?.message}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="username"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="用户名"
                      fullWidth
                      required
                      disabled // 编辑时不允许修改用户名
                      error={!!errors.username}
                      helperText={errors.username?.message || '用户名创建后不可修改'}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <PersonIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="profile.email"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="邮箱地址"
                      type="email"
                      fullWidth
                      required
                      error={!!errors.profile?.email}
                      helperText={errors.profile?.email?.message}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <EmailIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="profile.phone"
                  control={control}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      label="手机号码"
                      fullWidth
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <PhoneIcon />
                          </InputAdornment>
                        ),
                      }}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="status"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>状态</InputLabel>
                      <Select {...field} label="状态">
                        <MenuItem value="active">启用</MenuItem>
                        <MenuItem value="inactive">禁用</MenuItem>
                        <MenuItem value="pending">待审核</MenuItem>
                        <MenuItem value="suspended">暂停</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              {/* 组织角色 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  组织和角色
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="organizationId"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth required>
                      <InputLabel>所属组织</InputLabel>
                      <Select
                        {...field}
                        label="所属组织"
                        error={!!errors.organizationId}
                      >
                        {organizationsData?.data?.map((org: any) => (
                          <MenuItem key={org.id} value={org.id}>
                            {org.name}
                          </MenuItem>
                        ))}
                      </Select>
                      {errors.organizationId && (
                        <Typography variant="caption" color="error" sx={{ mt: 1 }}>
                          {errors.organizationId.message}
                        </Typography>
                      )}
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="roles"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={rolesData || []}
                      getOptionLabel={(option: any) => option.name}
                      value={rolesData?.filter((role: any) => field.value.includes(role.id)) || []}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map((role: any) => role.id));
                      }}
                      renderTags={(value, getTagProps) =>
                        value.map((option: any, index) => (
                          <Chip
                            key={option.id}
                            label={option.name}
                            {...getTagProps({ index })}
                          />
                        ))
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="用户角色"
                          required
                          error={!!errors.roles}
                          helperText={errors.roles?.message}
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="departments"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={departmentsData || []}
                      getOptionLabel={(option: any) => option.name}
                      value={departmentsData?.filter((dept: any) => field.value?.includes(dept.id)) || []}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map((dept: any) => dept.id));
                      }}
                      renderTags={(value, getTagProps) =>
                        value.map((option: any, index) => (
                          <Chip
                            key={option.id}
                            label={option.name}
                            {...getTagProps({ index })}
                          />
                        ))
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="所属部门"
                          placeholder="选择部门..."
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="positions"
                  control={control}
                  render={({ field }) => (
                    <Autocomplete
                      multiple
                      options={positionsData || []}
                      getOptionLabel={(option: any) => option.name}
                      value={positionsData?.filter((pos: any) => field.value?.includes(pos.id)) || []}
                      onChange={(_, newValue) => {
                        field.onChange(newValue.map((pos: any) => pos.id));
                      }}
                      renderTags={(value, getTagProps) =>
                        value.map((option: any, index) => (
                          <Chip
                            key={option.id}
                            label={option.name}
                            {...getTagProps({ index })}
                          />
                        ))
                      }
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="担任岗位"
                          placeholder="选择岗位..."
                        />
                      )}
                    />
                  )}
                />
              </Grid>

              {/* 安全设置 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  安全设置
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="security.twoFactorEnabled"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="启用两步验证"
                    />
                  )}
                />
              </Grid>

              <Grid item xs={12} md={6}>
                <Controller
                  name="security.loginNotification"
                  control={control}
                  render={({ field }) => (
                    <FormControlLabel
                      control={<Switch {...field} checked={field.value} />}
                      label="登录通知"
                    />
                  )}
                />
              </Grid>

              {/* 偏好设置 */}
              <Grid item xs={12}>
                <Typography variant="h6" gutterBottom sx={{ mt: 2 }}>
                  偏好设置
                </Typography>
                <Divider sx={{ mb: 2 }} />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="preferences.theme"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>主题</InputLabel>
                      <Select {...field} label="主题">
                        <MenuItem value="light">浅色</MenuItem>
                        <MenuItem value="dark">深色</MenuItem>
                        <MenuItem value="auto">自动</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="preferences.language"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>语言</InputLabel>
                      <Select {...field} label="语言">
                        <MenuItem value="zh-CN">简体中文</MenuItem>
                        <MenuItem value="en-US">English</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              <Grid item xs={12} md={4}>
                <Controller
                  name="preferences.timezone"
                  control={control}
                  render={({ field }) => (
                    <FormControl fullWidth>
                      <InputLabel>时区</InputLabel>
                      <Select {...field} label="时区">
                        <MenuItem value="Asia/Shanghai">北京时间</MenuItem>
                        <MenuItem value="America/New_York">纽约时间</MenuItem>
                        <MenuItem value="Europe/London">伦敦时间</MenuItem>
                      </Select>
                    </FormControl>
                  )}
                />
              </Grid>

              {/* 操作按钮 */}
              <Grid item xs={12}>
                <Box sx={{ display: 'flex', gap: 2, justifyContent: 'flex-end', mt: 3 }}>
                  <Button
                    variant="outlined"
                    startIcon={<CancelIcon />}
                    onClick={() => navigate('/users')}
                    disabled={isSubmitting}
                  >
                    取消
                  </Button>
                  <Button
                    type="submit"
                    variant="contained"
                    startIcon={<SaveIcon />}
                    disabled={isSubmitting || !hasPermission('user.edit')}
                  >
                    {isSubmitting ? '更新中...' : '更新用户'}
                  </Button>
                </Box>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Box>
  );
};

export default UserEditPage;